package cn.org.tpeach.nosql.service;

import cn.org.tpeach.nosql.controller.RedisApplication;
import cn.org.tpeach.nosql.framework.LogMsg;
import javafx.application.Platform;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextArea;
import lombok.extern.slf4j.Slf4j;

import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 日志面板接受日志
 */
@Slf4j
public  class LogTextFlowAppender implements Observer {
    private AtomicInteger count = new AtomicInteger(0);
    @Override
    public void update(Observable o, Object arg) {
        if(arg instanceof LogMsg){
            Platform.runLater(()->{
                LogMsg logMsg = (LogMsg) arg;
                appendText(logMsg);
            });
        }
    }

    private synchronized void appendText(LogMsg logMsg){
        try {
            TextArea logTextArea = RedisApplication.mainController.getLogTextArea();
            MenuItem clearItem = (MenuItem) logTextArea.getUserData();
            if(clearItem != null){
                logTextArea.setUserData(null);
                clearItem.setOnAction(event -> {
                    logTextArea.setText("");
                    count.set(0);
                });
            }
            if(count.get() > 200){
                String text = logTextArea.getText();
                int i = text.indexOf("\t\n");
                logTextArea.deleteText(0,i+2);
                count.getAndDecrement();
            }
            count.getAndIncrement();
            logTextArea.appendText(logMsg.toString()+"\t\n");
        }catch (Exception e){
            log.error("LogTextFlowAppender 接受消息异常",e);
        }
    }
}
